package com.htfyun.ft;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.htfyun.ft.agingtest.AgingBooleanSettingsAttr;
import com.htfyun.ft.agingtest.AgingDetailActivity;
import com.htfyun.ft.agingtest.AgingHardwareItemAttr;
import com.htfyun.ft.agingtest.AgingTestItemAttr;
import com.htfyun.ft.common.BatteryInfo;
import com.htfyun.ft.common.FTUtils;
import com.htfyun.ft.config.FTBuildConfig;
import com.htfyun.ft.config.NVRomKeysAttr;
import com.htfyun.ft.device.DeviceAttr;
import com.htfyun.ft.fragment.factory.FactoryTestItemsEnum;
import com.htfyun.ft.pccommand.PCCommand;
import com.htfyun.ft.showinfo.ShowInfoBean;
import com.htfyun.ft.showinfo.ShowInfoItemEnum;
import com.htfyun.ft.showinfo.ShowInfoSingleton;
import com.htfyun.ft.utils.DebugLog;
import com.htfyun.ft.utils.SystemPropertyUtil;
import com.htfyun.ft.utils.UsefulUtils;
import com.htfyun.ft.view.recyclerviewflexibledivider.HorizontalDividerItemDecoration;
import com.htfyun.hardware.NVRomController;
import com.htfyun.serialport.ServoSingleton;
import com.htfyun.serialport.uartservo.OnServoListener;
import com.htfyun.serialport.uartservo.ServoControlAttr;
import com.htfyun.serialport.uartservo.ServoErrorAttr;
import com.htfyun.serialport.uartservo.ServoInterestedInfo;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseActivity implements View.OnClickListener{

    private Context mContext;

    private RecyclerView recyclerViewInfo;
    private RecyclerViewAdapterShowInfoItems adapterShowInfoItems;
    private BatteryInfo batteryInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mContext = this;

        batteryInfo = new BatteryInfo(mContext);

        TextView welcome = findViewById(R.id.welcome);

        final String productName = SystemPropertyUtil.getSystemProperty("ro.build.product");
        final String productVersion = SystemPropertyUtil.getSystemProperty("ro.product.version");
        welcome.setText(getString(R.string.welcome, UsefulUtils.getAppVersion(mContext), productName, productVersion));

        View view = findViewById(R.id.btnSystemLauncher);
        if (view != null) {
            view.setOnClickListener(this);
        }

        initBtn(R.id.btnSystemLauncher);
        if (DeviceAttr.isNVRomKeySupported(NVRomKeysAttr.servo)) {
            initBtn(R.id.btnServoTune);

            ServoSingleton.INSTANCE.getServoControl().registerServoListener(servoListener);
            getHandler().sendEmptyMessageDelayed(MSG_SERVO_GET_ANGLE_AREA, PERIOD_SERVO_GET_ANGLE_AREA);

        } else {
            View servoTune = findViewById(R.id.btnServoTune);
            if (servoTune != null) {
                servoTune.setVisibility(View.GONE);
            }
        }
        initBtn(R.id.btnEngineerTest);
        initBtn(R.id.btnAgingTest);
        initBtn(R.id.btnFactoryTest);

        initBtn(R.id.txtAgingTestDetail);

        initBtn(R.id.btnFreshShowInfo);

        initViewForInfo();

        if (!FTUtils.isPCChecked()) {
            FTUtils.startFTFloat();
        }

        setBatteryMonitorEnabled(true);
        startSaveBatteryInfo();

    }

    @Override
    protected void onResume() {
        super.onResume();


        if (FTUtils.isKeepAgingAfterReboot()) {
            FTUtils.startAgingActivityAfterReboot();
        }

        registerReceiver(pccommandReceiver, getPCCommandIntentFilter());

        setBtnFactoryShowByCheckFTPassedAndBSN();

        updateTxtAgingTestDetail();

        // update ShowInfoBean
        ShowInfoBean b = ShowInfoSingleton.INSTANCE.getShowInfoBean(ShowInfoItemEnum.ft_test, null);
        adapterShowInfoItems.notifyBeanChanged(b);
        b = ShowInfoSingleton.INSTANCE.getShowInfoBean(ShowInfoItemEnum.wmac, null);
        adapterShowInfoItems.notifyBeanChanged(b);

        if (DeviceAttr.isNVRomKeySupported(NVRomKeysAttr.servo)) {
            ServoSingleton.INSTANCE.getServoControl().setFeedbackTime_100ms(0);
            ServoSingleton.INSTANCE.getServoControl().servoStop();
            ServoSingleton.INSTANCE.getServoControl().servoStop();
        }

    }

    @Override
    protected void onPause() {
        super.onPause();

        unregisterReceiver(pccommandReceiver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        DebugLog.e("MainActivity onDestroy");

        setBatteryMonitorEnabled(false);
        stopSaveBatteryInfo();

        if (DeviceAttr.isNVRomKeySupported(NVRomKeysAttr.servo)) {
            ServoSingleton.INSTANCE.deInit();
        }

    }

    private void updateTxtAgingTestDetail() {

        TextView txt = findViewById(R.id.txtAgingTestDetail);
        if (txt == null) {
            return;
        }

        if (!AgingTestItemAttr.agingHasDetail()) {
            txt.setVisibility(View.INVISIBLE);
            return;
        }

        txt.setVisibility(View.VISIBLE);

        txt.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);

        boolean agingOk = AgingBooleanSettingsAttr.aging_test_ok.get();

        int resId = R.string.aging_test_item_not_over;
        int color = Color.RED;
        if (agingOk) {
            resId = R.string.aging_test_item_over;
            color = Color.BLUE;
        }
        String over = getString(resId);
        txt.setText(getString(R.string.aging_test_detail, over));
        txt.setTextColor(color);
    }

    private void setBtnFactoryShowByCheckFTPassedAndBSN() {

        if (!DeviceAttr.isNVRomKeySupported(NVRomKeysAttr.bsn)) {
            return;
        }

        boolean validBsn = true;
        String bsn = NVRomController.getInstance().getNVRomString(NVRomKeysAttr.bsn.getKey());
        if (TextUtils.isEmpty(bsn) || bsn.length() < 5) {
            validBsn = false;
        }

        setViewEnabled(R.id.btnFactoryTest, !FTUtils.isFTPassed() && validBsn);

        if (FTUtils.isPCChecked()) {
            FTUtils.stopFTFloat();
        }

        FTFloatWindowService.setFloatLayoutShow(!FTUtils.isPCChecked());

    }

    private void initBtn(int resId) {
        View view = findViewById(resId);
        if (view != null) {
            view.setOnClickListener(this);
        }
    }

    private void setViewEnabled(int resId, boolean enabled) {
        View view = findViewById(resId);
        if (view != null) {
            view.setEnabled(enabled);
        }
    }

    private void initViewForInfo() {
        recyclerViewInfo = findViewById(R.id.recyclerViewInfo);

        if (recyclerViewInfo == null) {
            return;
        }

        recyclerViewInfo.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerViewInfo.addItemDecoration(new HorizontalDividerItemDecoration
                .Builder(getContext()).color(Color.BLACK).size(1).showLastDivider().build());

        adapterShowInfoItems = new RecyclerViewAdapterShowInfoItems(getContext(), getShowInfoBeanList());

        recyclerViewInfo.setAdapter(adapterShowInfoItems);

    }

    private List<ShowInfoBean> getShowInfoBeanList() {

        List<ShowInfoBean> showInfoBeanList = new ArrayList<>();

        for (ShowInfoItemEnum item : ShowInfoItemEnum.values()) {

            if (item.isShow()) {
                showInfoBeanList.add(ShowInfoSingleton.INSTANCE.getShowInfoBean(item, null));
            }
        }

        return showInfoBeanList;
    }

    @Override
    public void onClick(View v) {

        final int id = v.getId();
        switch (id) {
            case R.id.btnSystemLauncher:
//                FTUtils.startDefaultHome();
                finish();
                break;
            case R.id.btnServoTune:
                FTUtils.startActivity(this, ServoTuneActivity.class);
                break;
            case R.id.btnEngineerTest:
                FTUtils.startEngineerActivity();
                break;
            case R.id.btnAgingTest:
                FTUtils.startAgingActivityForSunty();
                break;
            case R.id.btnFactoryTest:
                FTUtils.startFTActivity();
                break;
            case R.id.txtAgingTestDetail:
                FTUtils.startActivity(getContext(), AgingDetailActivity.class);
                break;
            case R.id.btnFreshShowInfo:
                freshAllShowInfo();
                break;
        }
    }


    private void setBatteryMonitorEnabled(boolean enabled) {
        if (enabled) {
            batteryInfo.setOnBatteryChangedListener(onBatteryChangedListener);
            batteryInfo.startMonitor();
        } else {
            batteryInfo.setOnBatteryChangedListener(null);
            batteryInfo.stopMonitor();
        }
    }

    private BatteryInfo.OnBatteryChangedListener onBatteryChangedListener =
            new BatteryInfo.OnBatteryChangedListener() {
                @Override
                public void onBatteryChangedListener(BatteryInfo info) {

                    ShowInfoBean bean = ShowInfoSingleton.INSTANCE.getShowInfoBean(ShowInfoItemEnum.battery, info);
                    adapterShowInfoItems.notifyBeanChanged(bean);

                }
            };

    //save battery info

    private void startSaveBatteryInfo() {
        getHandler().sendEmptyMessage(MSG_SAVE_BATTERY_INFO);
    }

    private void stopSaveBatteryInfo() {
        getHandler().removeMessages(MSG_SAVE_BATTERY_INFO);
    }

    private void saveBatteryInfo() {
        if (batteryInfo == null) {
            return;
        }
        DebugLog.saveBatteryInfo(getBatteryInfo(batteryInfo));
    }

    private String getBatteryInfo(BatteryInfo info) {

        return getString(R.string.battery_info,
                info.getBatteryVoltage(),
                info.getBatteryLevel(),
                info.getBatteryStatusString(),
                info.getBatteryCurrent_mA());
    }


    private IntentFilter getPCCommandIntentFilter() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(PCCommand.PC_ACTION_NVROM_UPDATE);
        return filter;
    }

    private void freshAllShowInfo() {
        List<ShowInfoBean> infoBeanList = adapterShowInfoItems.getShowInfoBeanList();
        for (ShowInfoBean bean : infoBeanList) {
            ShowInfoItemEnum item = bean.getTestItemsEnum();
            if (item != null && item.isShow() && item != ShowInfoItemEnum.servo) {
                ShowInfoBean b = ShowInfoSingleton.INSTANCE.getShowInfoBean(item, null);
                adapterShowInfoItems.notifyBeanChanged(b);
            }
        }

        ShowInfoBean b = ShowInfoSingleton.INSTANCE.getShowInfoBean(ShowInfoItemEnum.ft_test, null);
        adapterShowInfoItems.notifyBeanChanged(b);

    }
    private BroadcastReceiver pccommandReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            final String action = intent.getAction();
            if (action == null) {
                return;
            }
            if (action.equals(PCCommand.PC_ACTION_NVROM_UPDATE)) {

                freshAllShowInfo();

                setBtnFactoryShowByCheckFTPassedAndBSN();
            }

        }
    };

    private OnServoListener servoListener =
            new OnServoListener() {
                private int count = 0;
                @Override
                public void onServoListener(List<ServoErrorAttr> list, ServoControlAttr servoControlAttr, ServoControlAttr.Instruction instruction, ServoInterestedInfo servoInterestedInfo) {

                    switch (servoControlAttr) {
                        case angle_area_min:
                        case angle_area_max:
                            count++;

                            if (count == 2) {
                                ServoSingleton.INSTANCE.getServoControl().unregisterServoListener(servoListener);
                                getHandler().removeMessages(MSG_SERVO_GET_ANGLE_AREA);

                                ShowInfoBean bean = ShowInfoSingleton.INSTANCE.getShowInfoBean(ShowInfoItemEnum.servo, servoInterestedInfo);
                                Message msg = getHandler().obtainMessage(MSG_UPDATE_SERVO, bean);
                                getHandler().sendMessageDelayed(msg, 500);

                            }
                            break;
                    }
                }
            };

    ////////////////////
    private final int MSG_SAVE_BATTERY_INFO = 1000;
    private final int PERIOD_SAVE_BATTERY_INFO = 60 * 1000;

    private final int MSG_SERVO_GET_ANGLE_AREA = 1001;
    private final int PERIOD_SERVO_GET_ANGLE_AREA = 300;
    private final int MSG_UPDATE_SERVO = 1002;

    @Override
    protected void handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_SAVE_BATTERY_INFO:
                saveBatteryInfo();
                getHandler().sendEmptyMessageDelayed(msg.what, PERIOD_SAVE_BATTERY_INFO);
                break;
            case MSG_SERVO_GET_ANGLE_AREA:
                ServoSingleton.INSTANCE.getServoControl().getAngleAreaMin();
                ServoSingleton.INSTANCE.getServoControl().getAngleAreaMax();
                getHandler().sendEmptyMessageDelayed(msg.what, PERIOD_SERVO_GET_ANGLE_AREA);
                break;
            case MSG_UPDATE_SERVO:
                if (msg.obj instanceof ShowInfoBean) {
                    adapterShowInfoItems.notifyBeanChanged((ShowInfoBean)msg.obj);
                }
                break;
        }
    }
}
